% this function returns the number of non-zero entries in the vector x
function [K,loc] = FindNonZeroValues(x,varargin)
Threshold = 1e-6;
if (length(varargin)>=1)
    Threshold = varargin{1};
end
n=length(x);
if (norm(x) < Threshold)
    K=0;
    loc = [];
else
    [sx,Ix] = sort(abs(x(:)));
    sx = flipud(sx); Ix = flipud(Ix);
    sxcumnorm = sqrt(cumsum(sx.^2));
    a = sxcumnorm(2:n)./sxcumnorm(1:(n-1)) - 1;
    aa = find(a < Threshold);
    if (numel(aa)==0)
        K = n;
        loc = 1:n;
    else
        K = aa(1);
        loc = Ix(1:K);
    end
end

